package com.meevle.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.red5.core.ApplicationSettings;

import com.meevle.business.SetDelegate;
import com.meevle.business.SlotDelegate;
import com.meevle.vo.SetVO;
import com.meevle.vo.SlotCommentVO;
import com.meevle.vo.SlotVO;
import com.meevle.vo.UserVO;

/**
 * Servlet implementation class ManageTrackAjaxServlet
 */
public class ManageTrackAjaxServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String serverURL = ApplicationSettings.getInstance().getServerUrl()+ApplicationSettings.getInstance().getContextPath().replace('\\', '/');
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ManageTrackAjaxServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
    	if(request.getParameter("getTrackComments") != null )
    		getTrackComments(request, response);
    	
    	else if(request.getParameter("addComment") != null)
    		addComment(request, response);
    	
    	else if(request.getParameter("getSetSlots") != null)
    		getSetSlots(request, response);
        
	}
    
	private void getTrackComments(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
        
        SetVO setVo = new SetVO();
        System.out.println("setName: " + request.getParameter("setName"));
        setVo.setName(request.getParameter("setName"));
        setVo.setOwner(new UserVO(request.getParameter("setOwnerUserName")));
        
        StringBuffer serverResponse = new StringBuffer();
        SlotVO slotVo = new SlotVO();
        
        slotVo.setDirectory("/streams" + request.getParameter("slotDirectory").split("streams")[1]);
        slotVo.setIndex(Integer.parseInt(request.getParameter("slotIndex")));
        
        serverResponse.append("<slot>");
        serverResponse.append("<slotAverageRating>"+calculateAverageRating(slotVo)+"</slotAverageRating>");
        serverResponse.append("<setAverageRating>"+SetDelegate.calculateAverageRating(setVo)+"</setAverageRating>");
        serverResponse.append("<track_comments>");
        try {
			List<SlotCommentVO> comments = SlotDelegate.getSlotComments(slotVo);
			
			for(SlotCommentVO comment : comments)
			{
				serverResponse.append("<track_comment>");
				serverResponse.append("<author>");
				serverResponse.append(comment.getAuthor().getUsername());
				serverResponse.append("</author>");
				serverResponse.append("<rating>");
				serverResponse.append(comment.getRating());
				serverResponse.append("</rating>");
				serverResponse.append("<comment>");
				serverResponse.append(comment.getComment());
				serverResponse.append("</comment>");
				serverResponse.append("<timestamp>");
				serverResponse.append(comment.getTimeStamp().toString());
				serverResponse.append("</timestamp>");
				serverResponse.append("</track_comment>");
				
			}
		} catch (IllegalArgumentException e1) {
			e1.printStackTrace();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
        
        try {
        	serverResponse.append("</track_comments>");
        	serverResponse.append("</slot>");
        	
        	System.out.println(serverResponse.toString());
        	
			response.getWriter().write(serverResponse.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void addComment(HttpServletRequest request, HttpServletResponse response)
	{
		SlotCommentVO comment = new SlotCommentVO();
		
		UserVO user = new UserVO();
		user.setUsername(request.getParameter("commentAuthorUserName"));
		
		SlotVO slotVo = new SlotVO();
		
        slotVo.setDirectory("/streams" + request.getParameter("slotDirectory").split("streams")[1]);
        slotVo.setIndex(Integer.parseInt(request.getParameter("slotIndex")));
        slotVo.setName(request.getParameter("slotName"));
        slotVo.setOwner(user);
        
        comment.setAuthor(user);
        comment.setComment(request.getParameter("comment"));
        comment.setRating(Integer.parseInt(request.getParameter("rating")));
        comment.setSlot(slotVo);
        comment.setTimeStamp(new Date(System.currentTimeMillis()));
        
        try {
			SlotDelegate.addCommentToSlot(comment);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		getTrackComments(request, response);
	}
	
	private void getSetSlots(HttpServletRequest request, HttpServletResponse response)
	{
		response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
        
        StringBuffer serverResponse = new StringBuffer();
        
        String setName = request.getParameter("setName");
        String ownerUserName = request.getParameter("setOwnerUserName");
        
        SetVO set = new SetVO();
        set.setName(setName);
        set.setOwner(new UserVO(ownerUserName));
        
        List<SlotVO> slots = new ArrayList<SlotVO>(1);
        try {
			slots = SetDelegate.getAllSlots(set);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		serverResponse.append("<slots>");
		for(SlotVO slot : slots)
		{
			serverResponse.append("<slot>");
			serverResponse.append("<slotName>"+slot.getName()+"</slotName>");
			serverResponse.append("<slotAuthor>"+slot.getOwner().getUsername()+"</slotAuthor>");
			serverResponse.append("<slotDirectory>"+serverURL+slot.getDirectory().replace("\\", "/")+"</slotDirectory>");
			serverResponse.append("<slotFileName>"+slot.getFilename()+"</slotFileName>");
			serverResponse.append("<slotIndex>"+slot.getIndex()+"</slotIndex>");
			serverResponse.append("<slotAverageRating>"+calculateAverageRating(slot)+"</slotAverageRating>");
			serverResponse.append("</slot>");
		}
		serverResponse.append("</slots>");
		
		try {
			System.out.println(serverResponse.toString());
			response.getWriter().write(serverResponse.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private double calculateAverageRating(SlotVO slot)
	{
		double average = 0;
		List<SlotCommentVO> comments = new ArrayList<SlotCommentVO>(0);
		try {
			comments = SlotDelegate.getSlotComments(slot);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(comments.size() > 0)
		{
			double sum = 0;
			for(SlotCommentVO comment : comments)
			{
				sum+=comment.getRating();
			}
			average = sum/comments.size();
		}
		return average;
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
